﻿using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Dapper;
using Mercury.Core.Configuration;
using Mercury.Core.DBManager;
using Mercury.Core.Enums;
using Mercury.Core.Extensions;
using Mercury.Core.Infrastructure;
using Mercury.Core.Utilities;
using Mercury.Entity.DomainModels;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace Mercury.System.Services
{
    public partial class Sys_LogService
    {
        private WebResponseContent _responseContent = new WebResponseContent();


        public override PageGridData<Sys_Log> GetPageData(PageDataOptions pageData)
        {
            var config = AppSetting.LogConfig;
            if (config == null || !config.Enable || !config.RealSubmaterStartDate.HasValue || config.RealSubmaterStartDate > DateTime.Now)
                return base.GetPageData(pageData);

            var queryParam = new Dictionary<string, object>();
            queryParam.Add("Order", pageData.Order);
            queryParam.Add("Page", pageData.Page);
            queryParam.Add("Rows", pageData.Rows);
            queryParam.Add("Sort", pageData.Sort);
            var list = new List<string>();
            var properties = typeof(Sys_Log).GetProperties();
            if (!string.IsNullOrEmpty(pageData.Wheres))
            {
                var param = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Param>>(pageData.Wheres);
                if (!param.Any(c => c.name == "BeginDate"))
                    param.Add(new Param { name = "BeginDate", value = DateTime.Now.ToString(), displayType = "lessorequal" });

                param.ForEach(item =>
                {
                    var field = item.name.ToString();
                    var pro = properties.FirstOrDefault(c => c.Name == field);
                    object value = item.value.ChangeType(pro.PropertyType); ;
                    var displayType = item.displayType;
                    if (displayType == "thanorequal")
                        field = field + "1";
                    if (displayType == "lessorequal")
                        field = field + "2";
                    queryParam.Add(field, value);
                });
                if (queryParam.Any(c => c.Key == "BeginDate1" || c.Key == "BeginDate2"))
                {
                    var endDate = DateTime.Now.Date.AddDays(1);
                    if (queryParam.Any(c => c.Key == "BeginDate2"))
                        endDate = Convert.ToDateTime(queryParam["BeginDate2"]).Date.AddDays(1);
                    var startDate = endDate.AddDays(-3);
                    if (queryParam.Any(c => c.Key == "BeginDate1"))
                        startDate = Convert.ToDateTime(queryParam["BeginDate1"]).Date;
                    if (startDate < config.RealSubmaterStartDate.Value)
                        list.Add("Sys_Log");

                    var sp = (startDate - config.RealSubmaterStartDate.Value).Days / config.Days;
                    if (sp < 0)
                        sp = 0;
                    var eDay = (endDate - config.RealSubmaterStartDate.Value).Days;

                    var ep = eDay / config.Days + (eDay % config.Days == 0 ? 0 : 1);

                    for (int i = sp; i < ep; i++)
                    {
                        var tempName = $"Sys_Log_{config.RealSubmaterStartDate.Value.AddDays(config.Days * i).ToLogTableNameStirng()}_{config.RealSubmaterStartDate.Value.AddDays(config.Days * (i + 1)).ToLogTableNameStirng()}";
                        list.Add(tempName);
                    }
                }
                if (list.Any())
                    queryParam.Add("Table", list.Aggregate((s, c) => s + "," + c));
            }
            var rows = repository.DapperContext.QueryList<Sys_Log>("PQueryLogsPageData", queryParam, CommandType.StoredProcedure);
            var result = new PageGridData<Sys_Log>() { rows = rows, total = rows.FirstOrDefault()?.Total ?? 0 };
            //dapper 目前只支持 .net5 这种写法有问题
            //using var grid = repository.DapperContext.QueryMultiple("PQueryLogsPageData", queryParam, CommandType.StoredProcedure);
            //result.rows = grid.Read<Sys_Log>().ToList();
            //var count = grid.ReadFirstOrDefault<int>();
            return result;
        }
    }

    public class Param
    {
        public string name { get; set; }
        public string value { get; set; }
        public string displayType { get; set; }
    }

    public class PageCount
    {
        public int Count { get; set; }
    }
}
